package com.smm.web.vmc.api;

import com.smm.web.vmc.domain.User;
import com.smm.web.vmc.dto.JsonReturn;
import com.smm.web.vmc.dto.UserDto;
import com.smm.web.vmc.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

/**
 * Created by zhenghao on 2016/9/29.
 *
 */
@Slf4j
@Controller
@RequestMapping(value = "/api",method = RequestMethod.POST)
public class LoginAPI {


    @Resource
    private UserService userService;

    @RequestMapping("/login.do")
    @ResponseBody
    public JsonReturn login(String account,String password,String clientid){

        try{

            if(StringUtils.isBlank(account) || StringUtils.isBlank(password)){

                throw  new Exception("账号或密码不能为空");
            }

            User user = userService.login(account, password);

            if(user==null){

                throw new Exception("账号或密码不正确");
            }

            //登录成功，更新用户clientid
            user.setClentid(clientid);

            userService.update(user);

            return new JsonReturn(1,"success",user);

        }catch (Exception e){

            e.printStackTrace();

            return new JsonReturn(0,e.getMessage());
        }

    }


    @RequestMapping("/regist.do")
    @ResponseBody
    public JsonReturn regist(UserDto user){

        log.info("---regist User :"+user.toString());

        try{

            User user1 = userService.regist(user);

            return new JsonReturn(1,"success",user1);

        }catch (Exception e){

            e.printStackTrace();

            return new JsonReturn(0,e.getMessage());
        }

    }


}
